﻿using System.IO;
using System.Windows.Media.Imaging;

namespace KinonekoSoftware.Drawings
{
    public static partial class Snapshot
    {
        public static RenderTargetBitmap Capture(FrameworkElement target, int ratio = 100)
        {
            if (target is null)
            {
                return null;
            }

            var w    = target.ActualWidth;
            var h    = target.ActualHeight;
            var dpi  = VisualTreeHelper.GetDpi(target);
            var dpiX = 96d * ratio / 100 * dpi.DpiScaleX;
            var dpiY = 96d * ratio / 100 * dpi.DpiScaleY;

            if (target is not Border root)
            {
                //
                // Windows 平台截图工作需要有Border参与,所以需要创建一个Dummy Border
                root = new Border
                {
                    Background = new VisualBrush
                    {
                        Visual = target,
                    },
                    Width  = w,
                    Height = h,
                };

                target.Measure(new Size(w, h));
                target.Arrange(new Rect(0, 0, w, h));
            }


            //
            // 创建RenderTargetBitmap
            var bitmap = new RenderTargetBitmap(
                                                (int)(w * dpiX / 96),
                                                (int)(h * dpiY / 96),
                                                dpiX,
                                                dpiY,
                                                PixelFormats.Pbgra32);


            bitmap.Render(root);
            return bitmap;
        }

        public static MemoryStream CaptureToStream(FrameworkElement target, int ratio = 100)
        {
            if (target is null)
            {
                return null;
            }

            var bitmap  = Capture(target, ratio);
            var ms      = new MemoryStream();
            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bitmap));
            encoder.Save(ms);

            ms.Seek(0, SeekOrigin.Begin);
            return ms;
        }
    }
}